package com.las.bot.cmd.qa;

import com.alibaba.fastjson.JSONObject;
import com.las.bot.common.Constant;
import com.las.bot.dao.QaAnswerDao;
import com.las.bot.dao.QaOptionDao;
import com.model.QaAnswer;
import com.model.QaOption;
import com.las.annotation.BotCmd;
import com.las.cmd.BaseNonCommand;
import com.las.utils.StrUtils;
import com.las.utils.mirai.CmdUtil;
import com.utils.RedisUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.ArrayList;

@BotCmd(funName = "问卷测试", isMatch = false)
public class QaAnswerCmd extends BaseNonCommand {

    private static Logger logger = Logger.getLogger(QaAnswerCmd.class);

    @Autowired
    private QaOptionDao qaOptionDao;

    @Autowired
    private QaAnswerDao qaAnswerDao;

    @Override
    public void execute(JSONObject obj, Long userId, Long id, Integer type, String command, ArrayList<String> args) throws Exception {
        Object answerInfo = RedisUtils.get("qa:tag:" + userId);
        if (null != answerInfo) {
            logger.info("问卷测试回答：" + command);
            if (type == Constant.MESSAGE_TYPE_GROUP) {
                CmdUtil.sendMessage("请私聊机器人发送该指令", userId, id, type);
                return;
            }
            if (StrUtils.isNumeric(command.trim())) {
                //纯数字才可以继续
                String answerStr = answerInfo.toString();
                String qId = answerStr.split("#")[0];
                String opNum = answerStr.split("#")[1];
                String opValue = command.trim();
                QaOption option = qaOptionDao.findByQaIdAndNum(qId, opNum);
                String opJson = option.getOpJson();
                String[] sp = opJson.split(",");
                for (int i = 0; i < sp.length; i++) {
                    if (Integer.parseInt(opValue) == (i + 1)) {
                        StringBuilder sb = new StringBuilder();
                        if (sp[i].contains("#")) {
                            String toNum = sp[i].split("#")[1].trim();
                            if (StrUtils.isNumeric(toNum)) {
                                QaOption nextOption = qaOptionDao.findByQaIdAndNum(qId, toNum);
                                String nextTitle = nextOption.getOpTitle();
                                sb.append(toNum).append("、").append(nextTitle).append("\n");
                                String[] nextSp = nextOption.getOpJson().split(",");
                                for (int j = 0; j < nextSp.length; j++) {
                                    String opStr = nextSp[j].split("#")[0];
                                    String toStr = nextSp[j].split("#")[1];
                                    sb.append(j + 1).append("、").append(opStr).append("(跳第").append(toStr).append("题)\n");
                                }
                                // 下一步记录跳到下一题的num
                                sb.append("回复选项值：1/2/3/4\n");
                                sb.append("\n测试时间默认是60分钟，超时会自动结束测试\n若不想测试也可以输入指令：#结束测试");
                                boolean tag = RedisUtils.set("qa:tag:" + userId, qId + "#" + toNum, 3600);
                                if (!tag) {
                                    CmdUtil.sendMessage("服务出现异常，请重试", userId, id, type);
                                    return;
                                }
                                if (StrUtils.isNotBlank(sb.toString())) {
                                    CmdUtil.sendMessage(sb.toString(), userId, id, type);
                                }
                            } else {
                                // 是一些字母则就是公开答案！
                                QaAnswer answer = qaAnswerDao.findByQaIdAndNum(qId, toNum);
                                sb.append("测试结束，测出您的结果如下：\n\n").append(answer.getAnswer());
                                RedisUtils.del("qa:tag:" + userId);
                                CmdUtil.sendMessage(sb.toString(), userId, id, type);
                            }
                        } else {
                            // 加分机制
                            String scoreStr = sp[i].split("-")[1].trim();
                            if (StrUtils.isNumeric(scoreStr)) {
                                int nextNum = Integer.parseInt(opNum) + 1;
                                QaOption nextOption = qaOptionDao.findByQaIdAndNum(qId, nextNum);
                                if (null != nextOption) {
                                    String nextTitle = nextOption.getOpTitle();
                                    sb.append(nextNum).append("、").append(nextTitle).append("\n");
                                    String[] nextSp = nextOption.getOpJson().split(",");
                                    for (int j = 0; j < nextSp.length; j++) {
                                        String opStr = nextSp[j].split("-")[0];
                                        String toStr = nextSp[j].split("-")[1];
                                        sb.append(j + 1).append("、").append(opStr).append("(加").append(toStr).append("分)\n");
                                    }
                                    sb.append("回复选项值：1/2/3/4\n");
                                    sb.append("\n测试时间默认是60分钟，超时会自动结束测试\n若不想测试也可以输入指令：#结束测试");
                                    boolean tag = RedisUtils.set("qa:tag:" + userId, qId + "#" + nextNum, 3600);
                                    if (!tag) {
                                        CmdUtil.sendMessage("服务出现异常，请重试", userId, id, type);
                                        return;
                                    }
                                    Object scoreObj = RedisUtils.get("qa:score:" + userId);
                                    if (null == scoreObj) {
                                        CmdUtil.sendMessage("服务出现异常，请重试", userId, id, type);
                                        return;
                                    }
                                    int score = Integer.parseInt(scoreObj.toString());
                                    score += Integer.parseInt(scoreStr);
                                    RedisUtils.set("qa:score:" + userId, score, 3600);
                                    if (StrUtils.isNotBlank(sb.toString())) {
                                        CmdUtil.sendMessage(sb.toString(), userId, id, type);
                                    }
                                } else {
                                    // 说明已经是上一次是最后一题，无法查到最后则公开分数
                                    Object scoreObj = RedisUtils.get("qa:score:" + userId);
                                    if (null != scoreObj) {
                                        int score = Integer.parseInt(scoreObj.toString());
                                        score += Integer.parseInt(scoreStr);
                                        QaAnswer answer = qaAnswerDao.findByQaIdAndScore(qId, score);
                                        sb.append("测试结束，您的分数共：").append(score).append("分。测试结果如下：\n\n");
                                        if (null == answer) {
                                            sb.append("分析结果暂无，有可能系统异常，请联系管理员");
                                        } else {
                                            sb.append(answer.getAnswer());
                                        }
                                        RedisUtils.del("qa:tag:" + userId);
                                        RedisUtils.del("qa:score:" + userId);
                                        CmdUtil.sendMessage(sb.toString(), userId, id, type);
                                    }
                                }

                            }

                        }

                        break;
                    }
                }
            }
        }

    }


}
